package cn.iocoder.yudao.module.crm.service.receipt;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.crm.dal.dataobject.contract.CrmContractDO;
import cn.iocoder.yudao.module.crm.enums.common.CrmAuditStatusEnum;
import cn.iocoder.yudao.module.crm.enums.common.CrmBizTypeEnum;
import cn.iocoder.yudao.module.crm.enums.permission.CrmPermissionLevelEnum;
import cn.iocoder.yudao.module.crm.service.permission.CrmPermissionService;
import cn.iocoder.yudao.module.crm.service.permission.bo.CrmPermissionCreateReqBO;
import com.mzt.logapi.context.LogRecordContext;
import com.mzt.logapi.starter.annotation.LogRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.crm.controller.admin.receipt.vo.*;
import cn.iocoder.yudao.module.crm.dal.dataobject.receipt.ReceiptDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.crm.dal.mysql.receipt.ReceiptMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.yudao.module.crm.enums.ErrorCodeConstants.*;
import static cn.iocoder.yudao.module.crm.enums.ErrorCodeConstants.RECEIPT_UPDATE_AUDIT_STATUS_FAIL_NOT_PROCESS;
import static cn.iocoder.yudao.module.crm.enums.LogRecordConstants.*;
import static cn.iocoder.yudao.module.crm.util.CrmAuditStatusUtils.convertBpmResultToAuditStatus;

/**
 * crm发票管理 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
@Slf4j
public class ReceiptServiceImpl implements ReceiptService {

    /**
     * BPM 发票审批流程标识
     */
    public static final String BPM_PROCESS_DEFINITION_KEY = "crm_receipt_audit";

    @Resource
    private ReceiptMapper receiptMapper;

    @Resource
    private CrmPermissionService permissionService;

    @Resource
    private BpmProcessInstanceApi bpmProcessInstanceApi;

    @Override
    public Long createReceipt(ReceiptSaveReqVO createReqVO, Long userId) {
        // 插入
        ReceiptDO receipt = BeanUtils.toBean(createReqVO, ReceiptDO.class);
        receiptMapper.insert(receipt);
        // 创建数据权限
        permissionService.createPermission(new CrmPermissionCreateReqBO().setUserId(userId)
                .setBizType(CrmBizTypeEnum.CRM_RECEIPT.getType()).setBizId(receipt.getId())
                .setLevel(CrmPermissionLevelEnum.OWNER.getLevel()));
        // 记录操作日志
        LogRecordContext.putVariable("receipt", receipt);
        // 返回
        return receipt.getId();
    }

    @Override
    public void updateReceipt(ReceiptSaveReqVO updateReqVO) {
        // 校验存在
        validateReceiptExists(updateReqVO.getId());
        // 更新
        ReceiptDO updateObj = BeanUtils.toBean(updateReqVO, ReceiptDO.class);
        receiptMapper.updateById(updateObj);
    }

    @Override
    public void deleteReceipt(Long id) {
        // 校验存在
        validateReceiptExists(id);
        // 删除
        receiptMapper.deleteById(id);

        // 删除数据权限
        permissionService.deletePermission(CrmBizTypeEnum.CRM_RECEIPT.getType(), id);
    }

    @Override
        public void deleteReceiptListByIds(List<Long> ids) {
        // 删除
        receiptMapper.deleteByIds(ids);
        }


    private void validateReceiptExists(Long id) {
        if (receiptMapper.selectById(id) == null) {
            throw exception(RECEIPT_NOT_EXISTS);
        }
    }

    @Override
    public ReceiptDO getReceipt(Long id) {
        return receiptMapper.selectById(id);
    }

    @Override
    public PageResult<ReceiptDO> getReceiptPage(ReceiptPageReqVO pageReqVO, Long userId) {
        return receiptMapper.selectPage(pageReqVO, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @LogRecord(type = CRM_RECEIPT_TYPE, subType = CRM_RECEIPT_SUBMIT_SUB_TYPE, bizNo = "{{#id}}",
            success = CRM_RECIEPT_SUBMIT_SUCCESS)
    public void submitReceipt(Long id, Long userId) {
        // 1. 校验发票是否在审批
        validateReceiptExists(id);
        ReceiptDO receipt = receiptMapper.selectById(id);
        if (ObjUtil.notEqual(receipt.getAuditStatus(), CrmAuditStatusEnum.DRAFT.getStatus())) {
            throw exception(RECEIPT_SUBMIT_FAIL_NOT_DRAFT);
        }

        // 2. 创建发票审批流程实例
        String processInstanceId = bpmProcessInstanceApi.createProcessInstance(userId, new BpmProcessInstanceCreateReqDTO()
                .setProcessDefinitionKey(BPM_PROCESS_DEFINITION_KEY).setBusinessKey(String.valueOf(id)));

        // 3. 更新发票工作流编号
        receiptMapper.updateById(new ReceiptDO().setId(id).setProcessInstanceId(processInstanceId)
                .setAuditStatus(CrmAuditStatusEnum.PROCESS.getStatus()));

        // 3. 记录日志
        LogRecordContext.putVariable("content", receipt.getContent());
    }

    @Override
    public void updateReceiptAuditStatus(Long id, Integer bpmResult) {
        // 1.1 校验发票是否存在
        validateReceiptExists(id);
        ReceiptDO receipt = receiptMapper.selectById(id);
        // 1.2 只有审批中，可以更新审批结果
        if (ObjUtil.notEqual(receipt.getAuditStatus(), CrmAuditStatusEnum.PROCESS.getStatus())) {
            log.error("[updateReceiptAuditStatus][receipt({}) 不处于审批中，无法更新审批结果({})]",
                    receipt.getId(), bpmResult);
            throw exception(RECEIPT_UPDATE_AUDIT_STATUS_FAIL_NOT_PROCESS);
        }

        // 2. 更新发票审批结果
        Integer auditStatus = convertBpmResultToAuditStatus(bpmResult);
        receiptMapper.updateById(new ReceiptDO().setId(id).setAuditStatus(auditStatus));
    }

    @Override
    public Long getAuditReceiptCount(Long userId) {
        return receiptMapper.selectCountByAudit(userId);
    }

}